#!/bin/bash

function start_logs() {
	cd ./docker
	docker-compose logs -f --tail ${TAIL:-10}
}

function web_start() {
	echo "Starting all agents and controllers, this may take a moment."

	
	BOKJIRO_AGENT_HOST=${BOKJIRO_AGENT_HOST:-"localhost"}

	MINISTRY_OF_WELFARE_HOST="ministry-of-welfare-agent"
	if [ -z "${PWD_HOST_FQDN}" ]; then
		DOCKERHOST=$(docker run --rm --net=host eclipse/che-ip)
		RUNMODE="docker"
	else
		PWD_HOST="${PWD_HOST_FQDN}"
		if [ "$PWD_HOST_FQDN" = "labs.play-with-docker.com" ]; then
			export ETH_CONFIG="eth1"
		elif [ "$PWD_HOST_FQDN" = "play-with-docker.vonx.io" ]; then
			export ETH_CONFIG="eth0"
		else
			export ETH_CONFIG="eth0"
		fi
		MY_HOST=$(ifconfig ${ETH_CONFIG} | grep inet | cut -d':' -f2 | cut -d' ' -f1 | sed 's/\./\-/g')
		BOKJIRO_AGENT_HOST="ip${MY_HOST}-${SESSION_ID}-8031.direct.${PWD_HOST_FQDN}"
		DOCKERHOST="ip${MY_HOST}-${SESSION_ID}-{PORT}.direct.${PWD_HOST_FQDN}"
		RUNMODE="pwd"
	fi

	AGENT_URLS=" BOKJIRO_AGENT_HOST=${BOKJIRO_AGENT_HOST} MINISTRY_OF_WELFARE_HOST=${MINISTRY_OF_WELFARE_HOST}"
	DOCKER_ENV="$AGENT_URLS RUNMODE=${RUNMODE} DOCKERHOST=${DOCKERHOST}"

	echo "Agent Hosts: ${AGENT_URLS}"

	if ! [ -z "$LEDGER_URL" ]; then
		GENESIS_URL="${LEDGER_URL}/genesis"
		DOCKER_ENV="$DOCKER_ENV LEDGER_URL=${LEDGER_URL} GENESIS_URL=${GENESIS_URL}"
	fi

	export $DOCKER_ENV

	docker-compose -f ./docker/docker-compose.yml up -d
	if [ "$LOGS" ]; then
		start_logs
	fi
	exit 0
}

function web_down() {
	docker-compose -f ./docker/docker-compose.yml down
	exit 0
}

function display_help() {
	help="$(basename "$0") [webstart|webdown|logs] [-h|--help] [-l|--logs]

1) webstart will start all agents and controllers in detached mode.
	Passing the additional logging option (-l|--logs) will follow and output logs to the terminal.

	Example usage: ./run_demo webstart [-l|logs]

2) webdown will stop all agents and controllers
	
	Example usage: ./run_demo webdown

3) logs will will attach to a currently running demo and output logs to the terminal
	Note: this will only work for an already running demo.

	Example: ./run_demo logs

Options:
	-h|--help  Help
	-l|--logs  Display and follow log output in terminal"
	echo "$help"
}

shopt -s nocasematch

cd $(dirname $0)

for i in "$@"
do
	case $i in
	-h|--help)
		display_help
		exit 0
	;;
	-l|--logs)
		LOGS=1
	;;
	webstart|webdown)
		DEMO=$i
	;;
	logs)
		start_logs
		exit 0
	;;
	esac
done

if [ "$DEMO" = "webstart" ]; then
	web_start
elif [ "$DEMO" = "webdown" ]; then
	web_down
else
	display_help
	exit 1
fi
